package com.jcooky.tutorfs.proxy;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcooky.tutorfs.proxy.filesystem.AbstractFileSystem;

public class Server {
	private static final Logger logger = LoggerFactory.getLogger(Server.class);
	private NioSocketAcceptor acceptor;
	private AbstractFileSystem fs = AbstractFileSystem.getFileSystem("hdfs");
	
	public void serve(int port) throws IOException {
		this.serve(port, new IoFilter[0]);
	}
	
	public void serve(int port, IoFilter[] filters) throws IOException {
		fs.open();
		
		acceptor = new NioSocketAcceptor(Runtime.getRuntime().availableProcessors() + 1);
		acceptor.setReuseAddress(true);
		int i = 0;
		for (IoFilter filter : filters) {
			acceptor.getFilterChain().addLast("filter" + i, filter);
		}
		acceptor.setHandler(new TutorFsProxyHandler(fs));
		acceptor.getSessionConfig().setBothIdleTime(1);
		
		acceptor.bind(new InetSocketAddress(port));
	}

	public void close() {
		if (acceptor != null) {
			for (IoSession session : acceptor.getManagedSessions().values()) {
				session.close(true);
			}
			acceptor.unbind();
			acceptor.dispose(true);
		}
		
		fs.close();
	}
}
